<template>
  <!-- 邀请页面主容器 -->
  <div class="invite-wrapper">
    <!-- 导航栏 -->
    <div class="invite-nav">
      <!-- 使用自定义头部组件 -->
      <head-top 
        :head-title="'邀请答主'" 
        :go-back="true" 
        @back="goBack"
      ></head-top>
    </div>

    <!-- 主要内容容器 -->
    <div class="invite-container">
      <!-- 已邀请区域 -->
      <div class="invite-section">
        <div class="invite-title">
          <span>已邀请(点击右上角保存)</span>
          <!-- 显示已邀请数量 -->
          <span class="invite-count">{{ invitedList.length }}/3</span>
          <!-- 保存按钮 -->
          <van-button 
            type="primary" 
            size="small" 
            class="save-btn" 
            @click="goBack"
          >
            保存
          </van-button>
        </div>

        <!-- 已邀请用户网格布局 -->
        <div class="invite-grid">
          <!-- 已邀请用户循环 -->
          <div
            v-for="(item) in invitedList"
            :key="item.id"
            class="invite-circle-container"
          >
            <div class="invite-circle filled">
              <!-- 用户头像 -->
              <img class="avatar-img" :src="getImageUrl(item.Avator)" />
            </div>
            <div class="invitee-name">{{ item.UserName }}</div>
            <!-- 取消邀请按钮 -->
            <van-button
              size="small"
              class="cancel-btn"
              @click="cancelInvite(item)"
            >
              取消
            </van-button>
          </div>

          <!-- 空位占位符 -->
          <div
            v-for="i in emptySlots"
            :key="'empty-' + i"
            class="invite-circle-container empty"
          >
            <div class="invite-circle empty-circle">
              <van-icon name="plus" size="24px" color="#ccc" />
            </div>
          </div>
        </div>
      </div>

      <div class="divider"></div>

      <!-- 推荐答主区域 -->
      <div class="recommend-section">
        <div class="recommend-title">推荐答主（{{ displayedRecommendList.length }}人）</div>
        <!-- 滚动容器，用于实现无限滚动 -->
        <div class="scroll-container" @scroll="handleScroll">
          <!-- 推荐列表循环 -->
          <van-cell v-for="item in displayedRecommendList" :key="item.UserId">
            <div class="recommend-item">
              <!-- 用户头像 -->
              <div class="avatar-circle">
                <img
                  v-if="item.Avator"
                  class="avatar-img"
                  :src="getImageUrl(item.Avator)"
                  @error="handleImageError"
                />
                <div v-else class="empty-avatar"></div>
              </div>

              <!-- 用户信息 -->
              <div class="user-info">
                <div class="name-wrapper">
                  <span class="name">{{ item.UserName }}</span>
                  <!-- 等级标签 -->
                  <van-tag :color="getLevelColor(item.Score)" class="level-tag">
                    Lv{{ item.Score }}
                  </van-tag>
                </div>
                <div class="company">
                  {{ item.CompanyName }} · {{ item.PositionName }}
                </div>
                <div class="stats">
                  <span>周解答率 {{ item.AnsweredNum }}%</span>
                  <span style="margin-left: 12px;">{{ item.AnsweringNum }}人排队中</span>
                </div>
              </div>

              <!-- 邀请按钮 -->
              <van-button
                size="small"
                :type="item.invited ? 'default' : 'primary'"
                :disabled="!item.invited && invitedList.length >= 3"
                class="invite-btn"
                hairline
                @click="toggleInvite(item)"
              >
                <template v-if="item.invited">
                  <van-icon name="success" /> 已邀请
                </template>
                <template v-else>
                  <van-icon name="plus" /> 邀请
                </template>
              </van-button>
            </div>
          </van-cell>

          <!-- 加载状态提示 -->
          <div v-if="loading" class="loading">加载中...</div>
          <div v-if="noMoreData" class="no-more-data">没有更多数据</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { 
  Button as VanButton,
  Icon as VanIcon,
  Tag as VanTag,
  Cell as VanCell,
  Toast 
} from 'vant';
import HeadTop from '@/components/header/Head.vue';
import axiosInstance from '@/plugins/axios';
import { mapState, mapMutations } from 'vuex'

export default {
  components: {
    HeadTop,
    VanButton,
    VanIcon,
    VanTag,
    VanCell,
  },
  data() {
    return {
      recommendList: [],        // 完整的推荐列表数据
      displayedRecommendList: [], // 当前显示的推荐列表（分页后）
      itemsPerPage: 10,         // 每页显示数量
      currentPage: 1,           // 当前页码
      loading: false,           // 加载状态
      noMoreData: false,        // 是否还有更多数据
    };
  },
  computed: {
    ...mapState(['invitedExperts']), // 从Vuex获取已邀请专家列表
    
    // 计算剩余空位数量
    emptySlots() {
      return Math.max(3 - this.invitedExperts.length, 0)
    },
    
    // 已邀请列表的getter/setter，与Vuex双向绑定
    invitedList: {
      get() { return this.invitedExperts },
      set(value) { this.SET_INVITED_EXPERTS(value) }
    }
  },
  async created() {
    try {
      await this.fetchRecommendList()
      // 初始化显示第一页数据
      this.displayedRecommendList = this.recommendList.slice(0, this.itemsPerPage)
    } catch (error) {
      Toast.fail('数据加载失败')
    }
  },
  methods: {
    ...mapMutations(['SET_INVITED_EXPERTS']), // Vuex mutation方法
    
    // 获取本地图片路径
    getImageUrl(avatar) {
      return `../../../dist/img/${avatar}`;
    },
    
    // 图片加载失败处理
    handleImageError(event) {
      event.target.style.display = 'none'
    },
    
    // 根据分数获取等级颜色
    getLevelColor(score) {
      if (score <= 3) return '#e8f5e9' // 绿色系
      if (score <= 5) return '#e3f2fd' // 蓝色系
      return '#f3e5f5'                 // 紫色系
    },
    
    // 切换邀请状态
    toggleInvite(item) {
      if (item.invited) {
        this.cancelInvite(item)
      } else {
        this.invite(item)
      }
      // 更新Vuex状态
      this.SET_INVITED_EXPERTS([...this.invitedList])
    },
    
    // 邀请操作
    invite(item) {
      if (this.invitedList.length >= 3) {
        Toast('最多邀请3位答主')
        return
      }
      item.invited = true
      this.invitedList = [...this.invitedList, { ...item }]
    },
    
    // 取消邀请
    cancelInvite(item) {
      // 更新推荐列表中的状态
      const target = this.recommendList.find(i => i.UserId === item.UserId)
      if (target) target.invited = false
      // 过滤出剩余已邀请用户
      this.invitedList = this.invitedList.filter(i => i.UserId !== item.UserId)
    },
    
    // 返回首页
    goBack() {
      this.$router.push('/index')
    },
    
    // 获取推荐列表数据
    async fetchRecommendList() {
      try {
        // 从Vuex获取筛选参数
        const companyId = this.$store.state.companyId || 1
        const departmentId = this.$store.state.departmentId
        const positionId = this.$store.state.positionId

        // API请求
        const response = await axiosInstance.post('https://xiaopaopao-api.xiaozhao.vip/VV/getListByPosition', {
          companyId: parseInt(companyId),
          departmentId: parseInt(departmentId),
          positionId: parseInt(positionId),
        })

        // 处理响应数据，合并邀请状态
        this.recommendList = response.data.map(item => ({
          ...item,
          invited: this.invitedList.some(expert => expert.UserId === item.UserId),
        }))
      } catch (error) {
        Toast.fail('加载推荐列表失败')
      }
    },
    
    // 滚动事件处理
    handleScroll(event) {
      const scrollContainer = event.target
      // 判断是否滚动到底部
      if (
        scrollContainer.scrollTop + scrollContainer.clientHeight >=
        scrollContainer.scrollHeight - 10
      ) {
        this.loadMore()
      }
    },
    
    // 加载更多数据
    async loadMore() {
      if (this.loading || this.noMoreData) return;

      this.loading = true;
      Toast.loading({
        message: '加载中...',
        duration: 0,
        forbidClick: true,
      });

      // 模拟异步加载
      setTimeout(() => {
        const start = this.currentPage * this.itemsPerPage;
        const end = start + this.itemsPerPage;
        const remainingItems = this.recommendList.length - start;

        // 判断是否还有数据
        if (remainingItems <= 0) {
          this.noMoreData = true;
          Toast('没有更多数据');
          this.loading = false;
          Toast.clear();
          return;
        }

        // 添加新数据
        const newItems = this.recommendList.slice(start, end);
        this.displayedRecommendList = [...this.displayedRecommendList, ...newItems];
        this.currentPage++;

        // 判断剩余数据是否不足一页
        if (remainingItems < this.itemsPerPage) {
          this.noMoreData = true;
          Toast('没有更多数据');
        }

        this.loading = false;
        Toast.clear();
      }, 800);
    },
  },
};
</script>

<style lang="scss">
@import '../style/invite'; // 引入样式文件
</style>